//
//  ZyaLogisticsDebtAlert.swift
//  SlaughterClient
//
//  Created by hudan on 2025/8/13.
//  Copyright © 2025 zwb. All rights reserved.
//

import UIKit
import ObjectMapper

class ZyaLogisticsDebtAlert: UIView {
    
    var sureBlock: (([ZyaAlertPerson]) -> Void)?
    
    private var persons = [ZyaAlertPerson]()
    
    private lazy var listView: UITableView = {
        let listView = UITableView(frame: .zero, style: .plain)
        listView.delegate = self
        listView.dataSource = self
        listView.tableFooterView = UIView()
        listView.separatorStyle = .none
        listView.register(ZyaAlertPersonCell.classForCoder(), forCellReuseIdentifier: ZyaAlertPersonCell.identifier)
        return listView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private let bgView = UIView().extBgColor(color: .white)
        .extRadius(radius: 5).extMaskBounds(mask: true)
        .extFrame(frame: .init(x: 30, y: KS_SCREEN_HEIGHT, width: KS_SCREEN_WIDTH - 2*30, height: 300))
    
    private func initUI() {
        extBgColor(color: .init(white: 0, alpha: 0.01))
        
        let touchBtn = UIButton()
        touchBtn.addTarget(self, action: #selector(hide), for: .touchUpInside)
        addSubview(touchBtn)
        touchBtn.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        
        addSubview(bgView)
        
        let titleLab = UILabel().easy("选择催款人", .black, .systemFont(ofSize: 17, weight: .medium))
            .extTextAligment(aligment: .center)
        bgView.addSubview(titleLab)
        titleLab.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(40)
        }
        
        
        let sureBtn = UIButton().easy("确定", Theme.primaryColor(), .systemFont(ofSize: 17, weight: .medium), nil, self, #selector(sureBtnClick))
            .extRadius(radius: 15).extMaskBounds(mask: true)
            .extBorderW(width: 1).extBorderColor(color: Theme.primaryColor())
        bgView.addSubview(sureBtn)
        sureBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 80, height: 30))
            make.bottom.equalToSuperview().offset(-10)
            make.centerX.equalToSuperview()
        }
        
        bgView.addSubview(listView)
        listView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(titleLab.snp.bottom).offset(10)
            make.bottom.equalTo(sureBtn.snp.top).offset(-10)
        }
    }
    
    func show(persons: [ZyaAlertPerson]) {
        
        guard let window = getKeyWindow() else {
            return
        }
        
        window.addSubview(self)
        
        self.persons = persons
        listView.reloadData()
        
        UIView.animate(withDuration: 0.3) {
            self.extBgColor(color: .init(white: 0, alpha: 0.4))
            self.bgView.ks_y = self.ks_centerY - 100
        }
    }
    
    @objc private func hide() {
        self.removeFromSuperview()
    }
    
    @objc func sureBtnClick() {
        
        let selectPerson = persons.filter { $0.isSelected }
        
        if selectPerson.count > 0 {
            sureBlock?(selectPerson)
            
            hide()
        } else {
            KSToast("请选择催款人")
        }
    }
}


extension ZyaLogisticsDebtAlert: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return persons.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ZyaAlertPersonCell.identifier) as! ZyaAlertPersonCell
        cell.model = persons[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let person = persons[indexPath.row]
        person.isSelected = !person.isSelected
        tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
}



class ZyaAlertPerson: Mappable {
    
    required public init?(map: Map){

    }
    
    public func mapping(map: Map) {
        id <- map["link_man_id"]
        name <- map["link_man"]
        linkOrgId <- (map["link_org_id"], StringTransform())
        linkManPhone <- (map["link_man_phone"], StringTransform())
    }

    /// Generates description of the object in the form of a NSDictionary.
    ///
    /// - returns: A Key value pair containing all valid values in the object.
    public func dictionaryRepresentation() -> [String: Any] {
      var dictionary: [String: Any] = [:]
      if let value = name { dictionary["link_man"] = value }
      if let value = id { dictionary["link_man_id"] = value }
        if let value = linkOrgId { dictionary["link_org_id"] = value }
        if let value = linkManPhone { dictionary["link_man_phone"] = value }

      return dictionary
    }
    
    var id: Int?
    var name: String?
    var linkOrgId: String?
    var linkManPhone: String?
    var isSelected: Bool = false
}


final class ZyaAlertPersonCell: UITableViewCell {
    //MARK: Public
    var model: ZyaAlertPerson? {
        didSet {
            guard let model = model else {
                return
            }
            
            selectImgView.image = model.isSelected ? UIImage(named: "selectedButton") : UIImage(named: "selectButton")
            
            if model.name?.contains("（今日已催款）") ?? false {
                let alert = "（今日已催款）"
                let attrStr = NSMutableAttributedString(string: model.name.unwrap)
                attrStr.addAttribute(.foregroundColor, value: UIColor(kshex: "666666"), range: .init(location: attrStr.length - alert.length, length: alert.length))
                nameLab.attributedText = attrStr
            } else {
                nameLab.text = model.name
            }
        }
    }
    
    private var selectImgView = UIImageView()
    
    private let nameLab = UILabel().easy(.darkGray, .systemFont(ofSize: 15))
    
    //MARK: UI
    func initUI() {
        addSubview(selectImgView)
        selectImgView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.width.height.equalTo(20)
            make.centerY.equalToSuperview()
        }
        
        addSubview(nameLab)
        nameLab.snp.makeConstraints { make in
            make.left.equalTo(selectImgView.snp.right).offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.bottom.equalToSuperview()
        }
    }
    
    //MARK:  Override
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {}
    override func setHighlighted(_ highlighted: Bool, animated: Bool) {}
    
}
